package load_balance

import (
	"errors"
	"fmt"
	"strings"
	"sync"
)

type RoundRobinBalance struct {
	curIndex      int64
	targetSvcList []string
	mu            sync.RWMutex
}

// 测试用的辅助方法
func (r *RoundRobinBalance) Add(params ...string) error {
	if len(params) == 0 {
		return errors.New("param len 1 at least")
	}
	addr := params[0]
	r.targetSvcList = append(r.targetSvcList, addr)
	return nil
}

func (r *RoundRobinBalance) Next() string {
	r.mu.RLock()
	defer r.mu.RUnlock()

	if len(r.targetSvcList) == 0 {
		return ""
	}

	idx := (r.curIndex + 1) % int64(len(r.targetSvcList))
	r.curIndex += 1
	return r.targetSvcList[idx]
}

func (r *RoundRobinBalance) Get(key string) (string, error) {
	return r.Next(), nil
}

func (r *RoundRobinBalance) Update(confLst []string) {
	fmt.Println("Update get check conf:", confLst)

	targetSvcList := make([]string, 0, len(confLst))
	for _, ip := range confLst {
		params := strings.Split(ip, ",")
		if len(params) == 0 {
			continue
		}
		targetSvcList = append(targetSvcList, params[0])
	}

	r.mu.Lock()
	r.targetSvcList = targetSvcList
	r.mu.Unlock()
}
